<template>
  <el-drawer v-model="drawer1" class="cupk2-data-form" :append-to-body="true" :with-header="false" size="500px">
    <div class="title">{{ typeTitle }}用户</div>
    <el-form v-loading="isLoading" :model="form" label-width="auto" ref="ruleFormRef" :disabled="!isAbledForm">

      <el-form-item label="姓名：" prop="name" :rules="v.getRules(true, 2, 16)">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="登录名：" prop="loginname" v-show="isShowLoginname"
        :rules="v.getRegExpRules(v.ValidRxs.loginname, true, 2, 32)">
        <el-input v-model="form.loginname" />
      </el-form-item>
      <el-form-item label="组织机构：" prop="orgid" :rules="v.getRules(true)">
        <el-tree-select :check-strictly='true' v-model="form.orgid" lazy :load="loadOrgidTreeNode" :props="orgidProps"
          style="width: 240px" />
      </el-form-item>
      <el-form-item label="用户角色：" prop="post">
        <el-select v-loading="isPostLoading" v-model="form.post" :multiple="true" placeholder="请选择">
          <el-option v-for="item in postOptions" :key="item.ID" :label="item.NAME" :value="item.ID" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户类型：" prop="type" :rules="v.getRules(true)">
        <el-select v-model="form.type" placeholder="请选择">
          <el-option label="系统用户" value="1" />
          <el-option label="超级管理员" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="state" :rules="v.getRules(true)">
        <el-switch v-model="form.state" active-value="1" inactive-value="0" />
      </el-form-item>
      <el-form-item label="备注：" prop="note" :rules="v.getRules(false, 0, 256)">
        <el-input v-model="form.note" autosize type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-row class="cupk2-form-button">
          <el-col :span="14">
            <el-button v-if="isShowSubmit" type="primary" @click="onSubmitForm(addData)">提交{{ typeTitle }}</el-button>
            <el-switch v-if="isShowRetain" v-model="isRetainForm" size="small" inactive-text="提交后保留表单" />
          </el-col>
          <el-col :span="10" class="cupk2-right">
            <el-button v-if="isShowReset" type="warning" @click="onResetForm">清空</el-button>
            <el-button v-if="isShowSubmit" type="info" plain @click="drawerWinOpen(false)">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script lang="ts" setup>

import { computed, inject, onMounted, reactive, ref } from 'vue';
import v from '@/hook/cupkFormValids';
import cupk2Request from '@/service/remoteRequests/Cupk2Request';
import { RequestTypeEnum } from '@/types/commons/RequestTypeEnum';
import notice from '@/components/msg/CupkNotice';
import { getCreatType, getUpdateType, getViewType, type FormParam } from '@/types/commons/FormType';
import type { DataResponse } from '@/types/commons/DataResponse';
import type { Emitter, EventType } from 'mitt';
import { PageEvent } from '@/types/commons/PageEvent';
import type { DataResult } from '@/types/commons/DataResult';

const loadOrgidTreeNode = (node: { data: { ID: string } }, resolve: (data: unknown) => void) => {
  const theRules = [];
  if (node.data.ID) {
    theRules.push({ key: 'parentid', value: node.data.ID, compara: '=' });
  }
  cupk2Request.search("api/localorg/tree", { rules: theRules })
    .then((remoteResult: DataResult) => {
      resolve(remoteResult.data);
    })
    .catch((msg: Error) => {
      notice.byError(msg.message);
    });
}
/**
 * 岗位选项表数据加载中
 */
const isPostLoading = ref(false);
/**
 * 岗位选项表的选项值
 */
const postOptions = ref<{ ID: string, NAME: string }[]>([]);
/**
 *加载岗位选项表
 */
const loadPost = () => {
  cupk2Request.submit("api/post/ables", RequestTypeEnum.post, isPostLoading, {})
    .then((response: DataResponse) => {
      Object.assign(postOptions.value, response.data);
    })
    .catch((msg: Error) => {
      notice.byError(msg.message);
    });
};


const orgidProps = {
  children: 'children',
  label: 'NAME',
  isLeaf: 'isLeaf'
}
const eventBus = inject('eventBus') as Emitter<Record<EventType, unknown>>;
const drawer1 = ref(false);

const isAbledForm = ref(false);

const ruleFormRef = ref()

const isLoading = ref(false);

const isRetainForm = ref(false);

const currentFormType = reactive<FormParam>({ type: getViewType(), id: '', data: {} });

const typeTitle = computed(() => {
  return currentFormType.type.title;
});;

const isShowReset = computed(() => {
  return currentFormType.type.key == getCreatType().key;
});

const isShowRetain = ref(true);


const isShowLoginname = ref(true);


const isShowSubmit = ref(true);


const form = reactive({
  id: '',
  post: [],
  loginname: '',
  name: '',
  type: '1',
  state: '1',
  note: '',
  orgid: '',
})


/**
 * 打开或关闭表单窗口
 * @param isOpen
 * @param formType
 */
const drawerWinOpen = (isOpen: boolean, formType?: FormParam) => {
  if (!isOpen) {
    drawer1.value = isOpen;
  } else {
    loadPost();
    Object.assign(currentFormType, formType);
    if (formType?.type.key == getCreatType().key) {
      initCreatForm();
    }
    if (formType?.type.key == getUpdateType().key) {
      initUpdateForm(formType.id);
    }
    if (formType?.type.key == getViewType().key) {
      initViewForm(formType.id);
    }
  }
};

/**
 * 初始化创建窗口
 */
const initCreatForm = () => {
  isShowSubmit.value = true;
  drawer1.value = true;
  isShowLoginname.value = true;
  form.id = '';
  isShowRetain.value = true;
  isAbledForm.value = true;
}

/**
 * 初始化更新窗口
 * @param id
 */
const initUpdateForm = (id: string | undefined) => {
  isShowSubmit.value = true;
  drawer1.value = true;
  isShowRetain.value = false;
  isShowLoginname.value = false;
  isAbledForm.value = true;
  if (!id) {
    notice.byError("id不能为空");
  } else {
    viewData(id);
  }
}

/**
 * 初始化浏览窗口
 * @param id
 */
const initViewForm = (id: string | undefined) => {
  isShowSubmit.value = false;
  drawer1.value = true;
  isShowRetain.value = false;
  isAbledForm.value = false;
  isShowLoginname.value = true;
  if (!id) {
    notice.byError("id不能为空");
  } else {
    viewData(id);
  }
}

/**
 * 展示信息（加载用户信息）
 */
const viewData = async (id: string) => {
  cupk2Request.submit('api/localuser/' + id, RequestTypeEnum.get, isLoading).then((response: DataResponse) => {
    Object.assign(form, response.data)
  }).catch((msg: Error) => {
    notice.byError(msg.message);
  });
}

/**
 * 执行提交按钮（创建/更新）
 */
const addData = async () => {

  if (currentFormType.type.key == getCreatType().key) {
    cupk2Request.submit('api/localuser', RequestTypeEnum.post, isLoading, form).then(() => {
      notice.bySuccess("创建成功!");
      reQuery();
      if (!isRetainForm.value) {
        onResetForm();
        drawerWinOpen(false);
      }
    }).catch((msg: Error) => {
      notice.byError(msg.message);
    });
  }

  if (currentFormType.type.key == getUpdateType().key) {
    cupk2Request.submit('api/localuser/' + form.id, RequestTypeEnum.put, isLoading, form).then(() => {
      notice.bySuccess("更新成功!");
      reQuery();
      onResetForm();
      drawerWinOpen(false);
    }).catch((msg: Error) => {
      notice.byError(msg.message);
    });
  }
}


/**清空表单 */
const onResetForm = () => {
  ruleFormRef.value.resetFields();
}

/**
 * 执行查询（提交表单后刷新数据）
 */
const reQuery = () => {
  eventBus.emit(PageEvent.data_do_query)
}

/**
 * 校验表单，准备提交
 * @param func
 */
const onSubmitForm = async (func: () => void) => {
  await ruleFormRef.value.validate((valid: boolean) => { if (valid) { func() } });
}

onMounted(() => {
  eventBus.on(PageEvent.data_form_open, (paras) => {
    drawerWinOpen((paras as { isOpen: boolean }).isOpen, (paras as { type: FormParam }).type);
  })
});
</script>
